import apiService from '@/utils/api-service.js'

/**
 * 用户登录服务工具类
 * 支持微信登录和手机号验证码登录
 */
class LoginService {
	constructor() {
		this.init()
	}

	init() {
		// 登录配置
		this.loginConfig = {
			// 是否开启云开发
			enableCloud: false,
			// Token存储键
			tokenKey: 'user_token',
			// 用户信息存储键
			userInfoKey: 'user_info',
			// 登录状态存储键
			loginStatusKey: 'login_status'
		}
		
		// 用户状态
		this.userState = {
			isLoggedIn: false,
			userInfo: null,
			token: null
		}
		
		// 初始化时检查登录状态
		this.checkLoginStatus()
	}

	/**
	 * 检查登录状态
	 * @returns {Promise<boolean>}
	 */
	checkLoginStatus() {
		return new Promise((resolve) => {
			try {
				// 从本地存储获取登录状态
				uni.getStorage({
					key: this.loginConfig.loginStatusKey,
					success: (res) => {
						if (res.data && res.data.isLoggedIn) {
							this.userState.isLoggedIn = true
							// 获取用户信息
							this.getUserInfo().then(userInfo => {
								if (userInfo) {
									this.userState.userInfo = userInfo
									resolve(true)
								} else {
									this.clearLoginStatus()
									resolve(false)
								}
							})
						} else {
							resolve(false)
						}
					},
					fail: () => {
						resolve(false)
					}
				})
			} catch (error) {
				console.error('LoginService - 检查登录状态失败:', error)
				resolve(false)
			}
		})
	}

	/**
	 * 微信登录
	 * @returns {Promise}
	 */
	wechatLogin() {
		return new Promise((resolve, reject) => {
			// 检查微信登录环境
			if (!uni.canIUse('getUserProfile')) {
				reject(new Error('当前微信版本不支持getUserProfile'))
				return
			}

			// 先获取用户授权
			uni.getUserProfile({
				desc: '用于完善用户资料',
				success: (profileRes) => {
					console.log('LoginService - 获取用户信息成功:', profileRes)
					
					// 获取登录凭证
					uni.login({
						provider: 'weixin',
						success: (loginRes) => {
							console.log('LoginService - 微信登录成功:', loginRes)
							
							// 构造用户信息
							const userInfo = {
								nickName: profileRes.userInfo.nickName,
								avatarUrl: profileRes.userInfo.avatarUrl,
								gender: profileRes.userInfo.gender,
								city: profileRes.userInfo.city,
								province: profileRes.userInfo.province,
								country: profileRes.userInfo.country,
								loginType: 'wechat',
								loginTime: new Date().getTime(),
								code: loginRes.code
							}
							
							resolve(userInfo)
						},
						fail: (error) => {
							console.error('LoginService - 微信登录失败:', error)
							reject(error)
						}
					})
				},
				fail: (error) => {
					console.error('LoginService - 获取用户信息失败:', error)
					reject(error)
				}
			})
		})
	}

	/**
	 * 手机号验证码登录
	 * @param {string} phoneNumber 手机号
	 * @param {string} verifyCode 验证码
	 * @returns {Promise}
	 */
	phoneLogin(phoneNumber, verifyCode) {
		return new Promise((resolve, reject) => {
			// 验证手机号格式
			if (!this.validatePhoneNumber(phoneNumber)) {
				reject(new Error('手机号格式不正确'))
				return
			}

			// 验证验证码格式
			if (!this.validateVerifyCode(verifyCode)) {
				reject(new Error('验证码格式不正确'))
				return
			}

			// 调用后端API进行登录
			const loginData = {
				phone: phoneNumber,
				verificationCode: verifyCode,
				loginType: 'SMS_CODE'
			}

			apiService.login(loginData)
				.then(response => {
					if (response.success) {
						// 登录成功，保存用户信息和token
						const authResponse = response.data
						const userInfo = {
							userId: authResponse.userId,
							phoneNumber: authResponse.userInfo.phone,
							nickName: authResponse.userInfo.nickname,
							avatarUrl: authResponse.userInfo.avatar,
							loginType: 'phone',
							loginTime: new Date().getTime(),
							accessToken: authResponse.accessToken,
							refreshToken: authResponse.refreshToken
						}

						// 保存认证token到apiService
						apiService.setToken(authResponse.accessToken)
						
						// 保存登录状态
						this.saveUserInfo(userInfo)
							.then(() => {
								this.userState.isLoggedIn = true
								this.userState.userInfo = userInfo
								this.userState.token = authResponse.accessToken
								resolve(userInfo)
							})
							.catch(reject)
					} else {
						reject(new Error(response.message || '登录失败'))
					}
				})
				.catch(error => {
					console.error('LoginService - 手机号登录失败:', error)
					reject(error)
				})
		})
	}

	/**
	 * 发送验证码
	 * @param {string} phoneNumber 手机号
	 * @returns {Promise}
	 */
	sendVerifyCode(phoneNumber) {
		return new Promise((resolve, reject) => {
			// 验证手机号格式
			if (!this.validatePhoneNumber(phoneNumber)) {
				reject(new Error('手机号格式不正确'))
				return
			}

			// 调用后端API发送验证码
			apiService.sendVerificationCode({
				phone: phoneNumber,
				type: 'LOGIN'
			})
				.then(response => {
					if (response.success) {
						console.log('LoginService - 验证码发送成功:', response)
						resolve(response)
					} else {
						reject(new Error(response.message || '验证码发送失败'))
					}
				})
				.catch(error => {
					console.error('LoginService - 发送验证码失败:', error)
					reject(error)
				})
		})
	}

	/**
	 * 获取微信手机号
	 * @param {Object} detail 微信授权数据
	 * @returns {Promise}
	 */
	getWechatPhoneNumber(detail) {
		return new Promise((resolve, reject) => {
			console.log('LoginService - 获取微信手机号:', detail)
			
			if (detail.errMsg === 'getPhoneNumber:ok') {
				// 实际应用中需要将encryptedData和iv发送到后端解密
				// 这里模拟解密结果
				const mockPhoneInfo = {
					phoneNumber: '138****8888',
					purePhoneNumber: '13888888888',
					countryCode: '86'
				}
				
				resolve(mockPhoneInfo)
			} else {
				reject(new Error('获取手机号失败'))
			}
		})
	}

	/**
	 * 获取微信用户头像和昵称
	 * @returns {Promise}
	 */
	getWechatUserProfile() {
		return new Promise((resolve, reject) => {
			// 检查微信登录环境
			if (!uni.canIUse('getUserProfile')) {
				reject(new Error('当前微信版本不支持getUserProfile'))
				return
			}

			// 获取用户授权
			uni.getUserProfile({
				desc: '用于完善用户资料',
				success: (profileRes) => {
					console.log('LoginService - 获取用户头像昵称成功:', profileRes)
					
					const userProfile = {
						nickName: profileRes.userInfo.nickName,
						avatarUrl: profileRes.userInfo.avatarUrl,
						gender: profileRes.userInfo.gender,
						city: profileRes.userInfo.city,
						province: profileRes.userInfo.province,
						country: profileRes.userInfo.country
					}
					
					resolve(userProfile)
				},
				fail: (error) => {
					console.error('LoginService - 获取用户头像昵称失败:', error)
					reject(new Error('获取用户信息失败'))
				}
			})
		})
	}

	/**
	 * 退出登录
	 * @returns {Promise}
	 */
	logout() {
		return new Promise((resolve) => {
			// 调用后端登出接口
			apiService.logout()
				.then(() => {
					console.log('LoginService - 登出成功')
				})
				.catch(error => {
					console.error('LoginService - 登出失败:', error)
				})
				.finally(() => {
					// 清除本地状态
					this.clearLoginStatus()
					this.userState.isLoggedIn = false
					this.userState.userInfo = null
					this.userState.token = null
					// 清除apiService中的token
					apiService.clearToken()
					resolve()
				})
		})
	}

	/**
	 * 获取用户信息
	 * @returns {Promise}
	 */
	getUserInfo() {
		return new Promise((resolve) => {
			uni.getStorage({
				key: this.loginConfig.userInfoKey,
				success: (res) => {
					resolve(res.data)
				},
				fail: () => {
					resolve(null)
				}
			})
		})
	}

	/**
	 * 保存用户信息
	 * @param {Object} userInfo 用户信息
	 * @returns {Promise}
	 */
	saveUserInfo(userInfo) {
		return new Promise((resolve, reject) => {
			// 保存用户信息
			uni.setStorage({
				key: this.loginConfig.userInfoKey,
				data: userInfo,
				success: () => {
					// 保存登录状态
					uni.setStorage({
						key: this.loginConfig.loginStatusKey,
						data: {
							isLoggedIn: true,
							loginTime: new Date().getTime()
						},
						success: () => {
							resolve(userInfo)
						},
						fail: reject
					})
				},
				fail: reject
			})
		})
	}

	/**
	 * 更新用户信息
	 * @param {Object} updateData 更新的数据
	 * @returns {Promise}
	 */
	updateUserInfo(updateData) {
		return new Promise((resolve, reject) => {
			this.getUserInfo().then(userInfo => {
				if (userInfo) {
					const updatedUserInfo = {
						...userInfo,
						...updateData,
						updateTime: new Date().getTime()
					}
					
					this.saveUserInfo(updatedUserInfo)
						.then(() => {
							this.userState.userInfo = updatedUserInfo
							resolve(updatedUserInfo)
						})
						.catch(reject)
				} else {
					reject(new Error('用户未登录'))
				}
			})
		})
	}

	/**
	 * 清除登录状态
	 */
	clearLoginStatus() {
		uni.removeStorage({ key: this.loginConfig.userInfoKey })
		uni.removeStorage({ key: this.loginConfig.loginStatusKey })
		uni.removeStorage({ key: this.loginConfig.tokenKey })
	}

	/**
	 * 验证手机号格式
	 * @param {string} phoneNumber 手机号
	 * @returns {boolean}
	 */
	validatePhoneNumber(phoneNumber) {
		const phoneRegex = /^1[3-9]\d{9}$/
		return phoneRegex.test(phoneNumber)
	}

	/**
	 * 验证验证码格式
	 * @param {string} verifyCode 验证码
	 * @returns {boolean}
	 */
	validateVerifyCode(verifyCode) {
		const codeRegex = /^\d{6}$/
		return codeRegex.test(verifyCode)
	}

	/**
	 * 生成用户ID
	 * @returns {string}
	 */
	generateUserId() {
		return 'user_' + new Date().getTime() + '_' + Math.random().toString(36).substr(2, 9)
	}

	/**
	 * 检查是否已登录
	 * @returns {boolean}
	 */
	isLoggedIn() {
		return this.userState.isLoggedIn
	}

	/**
	 * 获取当前用户信息
	 * @returns {Object|null}
	 */
	getCurrentUserInfo() {
		return this.userState.userInfo
	}

	/**
	 * 强制登录检查
	 * @param {string} tip 提示信息
	 * @returns {Promise<boolean>}
	 */
	requireLogin(tip = '请先登录') {
		return new Promise((resolve) => {
			if (this.isLoggedIn()) {
				resolve(true)
			} else {
				uni.showModal({
					title: '提示',
					content: tip,
					confirmText: '去登录',
					success: (res) => {
						if (res.confirm) {
							// 跳转到登录页面
							uni.navigateTo({
								url: '/pages/login/login'
							})
						}
						resolve(false)
					}
				})
			}
		})
	}
}

export { LoginService }
export default LoginService